/*
 * For com.royal.art
 * Copyright [2015/11/16] By RICK
 */
package com.cntaiping.royal.bass.system.interceptor;

import com.cntaiping.royal.bass.system.common.GlobalVariableNames;
import com.cntaiping.royal.bass.system.context.GlobalContext;
import com.google.common.base.Splitter;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * AuthInterceptor
 * 用户登录认证
 * @author FCHEN
 * @date 2015/11/16
 */
public class AuthInterceptor extends AbstractHandlerInterceptor {

    /**
     * 忽略列表
     */
    private List<String> ignoreUrls;

    public AuthInterceptor(){
        ignoreUrls =Splitter.on("|").splitToList(GlobalContext.getProperties(GlobalVariableNames.INGOREAUTH));
    }


    /**
     * 后台登录认证 目前直接按照session中用户处理
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        if ( isIgnoreUrls( request.getServletPath())
//            || request.getSession().getAttribute(GlobalVariableNames.LOGINUSER) != null ) {
//            return true;
//        }
//        response.sendRedirect(GlobalContext.getProperties(GlobalVariableNames.BASEPATH) + "/auth/login");
//        return false;
        return true;
    }

    /**
     * 是否是忽略url
     * @param servletPath
     * @return
     */
    private boolean isIgnoreUrls(String servletPath){
        String suffix = StringUtils.substringAfterLast(servletPath,".");
        suffix = StringUtils.isBlank(suffix) ? null : "."+suffix;
        String pre =StringUtils.substringBeforeLast(servletPath,".");
        boolean ignore = false;
        for(String s : ignoreUrls){
            if(ignore = s.equals(suffix)){
                break;
            } else if(ignore = pre.endsWith(s)){
                break;
            }
        }
        return ignore;
    }

}
